package com.lucher.mes.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lucher.mes.common.Tools;
import com.lucher.mes.dao.DepotrackinfoMapper;
import com.lucher.mes.dao.ProductMapper;
import com.lucher.mes.dao.ProductdepotMapper;
import com.lucher.mes.dao.ProductinoutMapper;
import com.lucher.mes.dao.OperatorMapper;
import com.lucher.mes.po.Depotrackinfo;
import com.lucher.mes.po.Product;
import com.lucher.mes.po.Productdepot;
import com.lucher.mes.po.Productinout;
import com.lucher.mes.po.Operator;
import com.lucher.mes.service.ICoderuleService;
import com.lucher.mes.service.IProductdepotService;

/**
 * 用户控制层
 */
@Controller
@Scope("prototype")
@RequestMapping("/productdepot")
@Transactional
public class ProductdepotController extends BaseController {

	@Autowired
	private ProductdepotMapper productdepotDao;
	@Autowired
	private IProductdepotService productdepotService;
	@Autowired
	private ProductMapper productDao;
	@Autowired
	private ICoderuleService coderuleService;
	@Autowired
	private ProductinoutMapper productinoutDao;
	@Autowired
	private OperatorMapper operatorDao;
	@Autowired
	private DepotrackinfoMapper depotrackinfoDao;
	
	/*
     * 特殊的instance变量
     * 注：零长度的byte数组对象创建起来将比任何对象都经济――查看编译后的字节码：
     * 生成零长度的byte[]对象只需3条操作码，而Object lock = new Object()则需要7行操作码。
     */
    private static byte[] lock = new byte[0];
	
	/**
	 * 查询材料库存
	 */
	@RequestMapping(value = "/findByList")
	public String findByList(Productdepot form) {
		return "productdepot/findProductdepotList";
	}
	
	/**
	 * 查询材料库存Json
	 */
	@ResponseBody
	@RequestMapping(value = "/findListJson")
	public Map<String, Object> findListJson(Productdepot form) {
		//封装JSon的Map
		Map<String, Object> result = new HashMap<String, Object>(); 
		List<HashMap<String, Object>> objectlist = new ArrayList<HashMap<String, Object>>();
		
		Integer total = productdepotDao.findByCount(form);
		List<Productdepot> list = productdepotDao.findByListForPage(form);
		for (Productdepot productdepot : list) {
			HashMap<String, Object> objectMap = new HashMap<String, Object>();
			objectMap.put("productcode", productdepot.getProductcode());
			objectMap.put("productname", productdepot.getProductname());
			objectMap.put("operatorcode", productdepot.getOperatorcode());
			objectMap.put("batchno", productdepot.getBatchno());
			objectMap.put("depotamount", productdepot.getDepotamount());
			objectMap.put("addtime", StringUtils.isEmpty(productdepot.getAddtime())?"":Tools.getStr(productdepot.getAddtime()).substring(0, 19));
			objectMap.put("inoutercode", productdepot.getInoutercode());
			objectMap.put("depotstatus", productdepot.getDepotstatus());
			objectMap.put("depotrackcode", productdepot.getDepotrackcode());
			objectMap.put("alarmdepotamount", productdepot.getAlarmdepotamount());
			objectMap.put("suppliername", productdepot.getSuppliername());
			objectMap.put("remark", productdepot.getRemark());
			
			objectlist.add(objectMap);
		}
		
		result.put("code", "0");
		result.put("count", total);//页面总数
		result.put("data", objectlist);
		return result;
	}
    
	/**
	 * 材料入库
	 */
	@RequestMapping(value = "/indepot")
	public String indepot(Productdepot form, Product record,Model model) {
		model.addAttribute("productlist", productDao.findByList(record));
		model.addAttribute("operatorlist", operatorDao.findOperatorList(new Operator()));
		model.addAttribute("depotrackinfolist", depotrackinfoDao.findByList(new Depotrackinfo()));
		
		return "productdepot/indepot";
	}
	
	/**
	 * 保存材料入库
	 */
	@RequestMapping(value = "/saveIndepot")
	@ResponseBody //此标志就是返回jesion数据给页面的标志
	public Map<String,Object> saveIndepot(Productdepot form) {
		
		//封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		
		Operator operator = (Operator)getSession().getAttribute("Operator");
		String currenttime = Tools.getCurrentTime();
		Product product = productDao.findByProductcode(form.getProductcode());
		if(product == null){
			responseJson.put("flag", "0"); //操作失败
			responseJson.put("msg", "操作失败，该材料不存在");
			return responseJson;
		}
		form.setProductname(product.getProductname());
		//获取材料批次号
		String batchno = productdepotService.getProductbatchno(form.getProductcode());
		//封装材料批次号
		form.setBatchno(batchno);
		//默认有库存
		form.setDepotstatus("有库存");
		//入库时间
		form.setAddtime(currenttime);
		//操作员
		form.setOperatorcode(operator.getLoginname());
		//材料入库保存
		productdepotDao.insertSelective(form);
		
		//增加材料入库记录
		Productinout productinout = new Productinout();
		productinout.setProductcode(form.getProductcode());
		productinout.setProductname(form.getProductname());
		productinout.setOperatorcode(operator.getLoginname());
		productinout.setBatchno(form.getBatchno());
		productinout.setType("入库");
		productinout.setInoutamount(form.getDepotamount());
		productinout.setAddtime(currenttime);
		productinout.setInoutercode(form.getInoutercode());
		productinout.setInoutstatus("已领");
		productinout.setDepotrackcode(form.getDepotrackcode());
		//入库记录保存
		productinoutDao.insertSelective(productinout);
		
		responseJson.put("flag", "1");//操作成功
		responseJson.put("msg", "操作成功");
		
		return responseJson;
	}
	
	/**
	 * 材料出库
	 */
	@RequestMapping(value = "/outdepot")
	public String outdepot(Productdepot form,Model model) {
		form.setProductdepot(productdepotDao.findByBatchno(form.getBatchno()));
		model.addAttribute("operatorlist", operatorDao.findOperatorList(new Operator()));
		return "productdepot/addOutdepot";
	}
	
	/**
	 * 保存材料出库
	 */
	@RequestMapping(value = "/saveOutdepot")
	@ResponseBody //此标志就是返回jesion数据给页面的标志
	public  Map<String,Object>  saveOutdepot(Productdepot form) {
		Operator operator = (Operator)getSession().getAttribute("Operator");
		
		//封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		
		//加锁
		synchronized(lock) {
			//查询材料库 存不存在此种产品
			Productdepot depot = productdepotDao.findByBatchno(form.getBatchno());
			if(depot != null){//有库存
				if("有库存".equals(depot.getDepotstatus())){
					//修改该产品库存量
					//已有库存量
					int depotamount = depot.getDepotamount();
					//本次出库量
					int inoutamount = form.getInoutamount();
					depot.setDepotamount(depotamount-inoutamount);
					if(depotamount-inoutamount < 0){
						responseJson.put("flag", "0"); //操作失败
						responseJson.put("msg", "操作失败，出库数量不能大于库存量！");
						return responseJson;
					}
					if(depotamount-inoutamount == 0){
						depot.setDepotstatus("无库存"); //无库存
					}
					
					productdepotDao.updateByPrimaryKeySelective(depot);
					
					//增加产品出库记录
					Productinout productinout = new Productinout();
					productinout.setProductcode(form.getProductcode());
					productinout.setProductname(form.getProductname());
					productinout.setOperatorcode(operator.getLoginname());
					productinout.setBatchno(form.getBatchno());
					productinout.setType("出库");
					productinout.setInoutamount(inoutamount);
					productinout.setAddtime(Tools.getCurrentTime());
					productinout.setInoutercode(operator.getLoginname());
					productinout.setInoutstatus("已领");
					productinout.setDepotrackcode(depot.getDepotrackcode());
					
					productinoutDao.insertSelective(productinout);
					
					responseJson.put("flag", "1"); 
					responseJson.put("msg", "操作成功");
					return responseJson;
				}else{ 
					responseJson.put("flag", "0"); //操作失败
					responseJson.put("msg", "操作失败，此产品不是库存状态！");
					return responseJson;
				}
			}else{
				responseJson.put("flag", "0"); //操作失败
				responseJson.put("msg", "操作失败，此产品在库存中不存在！");
				return responseJson;
			}
		}
	}
	
	/**
	 * 手动修改库存量
	 */
	@RequestMapping(value = "/updateDepotamountInit")
	public String updateDepotamountInit(Productdepot form,Model model) {
		form.setProductdepot(productdepotDao.findByBatchno(form.getBatchno()));
		model.addAttribute("operatorlist", operatorDao.findOperatorList(new Operator()));
		return "productdepot/updateDepotamount";
	}
	
	/**
	 * 保存库存量的修改
	 */
	@RequestMapping(value = "/updateDepotamount")
	@ResponseBody //此标志就是返回jesion数据给页面的标志
	public Map<String,Object>  updateDepotamount(Productdepot form) {
		Operator operator = (Operator)getSession().getAttribute("Operator");
		
		//封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		
		//加锁
		synchronized(lock) {
			//查询材料库存不存在此种产品
			Productdepot depot = productdepotDao.findByBatchno(form.getBatchno());
			
			if(depot == null){
				responseJson.put("flag", "0"); //操作失败
				responseJson.put("msg", "操作失败，此批次号不存在！");
				return responseJson;
			}
		
			//修改该产品库存量
			//已有库存量
			int depotamount = depot.getDepotamount();
			//本次入库量
			int inoutamount = form.getInoutamount();
			depot.setDepotamount(depotamount+inoutamount);
			
			if(depotamount+inoutamount > 0){
				depot.setDepotstatus("有库存"); //有库存
			}
			
			productdepotDao.updateByPrimaryKeySelective(depot);
			
			//增加产品入库记录
			Productinout productinout = new Productinout();
			productinout.setProductcode(form.getProductcode());
			productinout.setProductname(form.getProductname());
			productinout.setOperatorcode(operator.getLoginname());
			productinout.setBatchno(form.getBatchno());
			productinout.setType("入库"); //入库
			productinout.setInoutamount(inoutamount);
			productinout.setAddtime(Tools.getCurrentTime());
			productinout.setInoutercode(form.getInoutercode());//操作员为负责人
			productinout.setInoutstatus("已领");
			productinout.setDepotrackcode(depot.getDepotrackcode());
			
			productinoutDao.insertSelective(productinout);
			
			responseJson.put("flag", "0"); //操作失败
			responseJson.put("msg", "操作成功");
			return responseJson;
		}
	}
	
	/**
	 * 编辑产品权限初始化页面
	 */
	@RequestMapping(value = "/updateInit")
	public String updateInit(Productdepot form) {
		form.setProductdepot(productdepotDao.selectByPrimaryKey(form.getId()));
		return "productdepot/updateProductdepot";
	}

	/**
	 * 保存编辑后产品权限
	 */
	@RequestMapping(value = "/update")
	public String update(Productdepot form) {
		productdepotDao.updateByPrimaryKeySelective(form);
		form.setReturninfo("修改成功");
		return updateInit(form);
	}

	/**
	 * 单个删除
	 */
	@ResponseBody //此标志就是返回jesion数据给页面的标志
	@RequestMapping(value = "/delete")
	public Map<String,Object> delete(Productdepot form) {
		//封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		//删除产品
		productdepotDao.deleteByPrimaryKey(form.getId());
		
		responseJson.put("flag", "1");//删除成功
		responseJson.put("msg", "删除成功");
		
		return responseJson;
	}
	
	
	/**
     * 获取下拉列表框Json值
     */
	@ResponseBody //此标签表示返回的数据不是html标签的页面，而是其他某种格式的数据时（如json、xml等）使用；
	@RequestMapping(value="/getProductdepotComboBoxJson")
	public List<Map<String,Object>> getProductdepotComboBoxJson(Productdepot form) { 
	    List<Productdepot> productdepotList = productdepotDao.findByList(form);
	    List<Map<String, Object>> objectComboBoxJson = new ArrayList<Map<String, Object>>();
	    //添加请选择项-默认为空，查询所有
	    //HashMap<String,Object> selectMap = new HashMap<String, Object>();
	    //selectMap.put("id", "");
	    //selectMap.put("text", "请选择");
	    //productComboBoxJson.add(selectMap);
	    
	    //封装属性结构信息
	    for(Productdepot productdepot:productdepotList){
	    	    HashMap<String,Object> objectMap = new HashMap<String, Object>();
	    	    objectMap.put("id", productdepot.getBatchno());
	    	    objectMap.put("text", productdepot.getBatchno() + "(" + productdepot.getProductname() + ")");
	    	    
	    	    objectComboBoxJson.add(objectMap);  
	    }  
	   return objectComboBoxJson;
	}  
}
